$(function() {
    // 处理优惠券显示
    if (useFindCoupon.use_id) selectCoupon(useFindCoupon);

    // 不存在默认收货地址的逻辑
    // if (0 == orderParamArr.isWeChat) $('input[name=addr_id]').val(0);

    // 自动加载默认的运费
    if (orderParamArr.addrID) selectAddress('addr_id', orderParamArr.addrID);

    // 显示隐藏更多收货地址
    if ($('#usersAddress div.address-item').length > 4) {
        $('#usersAddress .more-btn').show();
    } else {
        $('#usersAddress .more-btn').hide();
    }
    $('.more-btn').click(function() {
        var showhide = $(this).attr('data-showhide');
        if ('hide' == showhide) {
            $('#usersAddress div.address-item').each(function(index, item) {
                if (index > 3) $(item).show();
            });
            $(this).attr('data-showhide', 'show');
            $(this).find('span').html('收起更多地址<i class="iconfont-normal"></i>');
        } else {
            $('#usersAddress div.address-item').each(function(index, item) {
                if (index > 3) $(item).hide();
            });
            $(this).attr('data-showhide', 'hide');
            $(this).find('span').html('显示更多地址<i class="iconfont-normal"></i>');
        }
    });

    var sign_selectCurAddr_click = false;
    // 选择该收货地址
    $('#selectCurAddr_1625108121').click(function(event) {
        sign_selectCurAddr_click = true;
        $('#selectCurAddrHtml_1625108329').hide();
        $("body, html").animate({ scrollTop: 0 }, 300); //返回顶部，用JQ的animate动画
    });

    // 窗体滚动事件
    $(window).scroll(function () {
        if (parseInt(orderParamArr.addrID) === 0) {
            var t_a = $("#goods-list_html").offset();
            //判断滚动条的垂直位置是否大于0，说白了就是：判断滚动条是否在顶部
            if ($(window).scrollTop() <= (t_a.top - 150)) {
                if ($(window).scrollTop() <= 0) sign_selectCurAddr_click = false;
                $('#selectCurAddrHtml_1625108329').hide();
            } else {
                if (sign_selectCurAddr_click == false) $('#selectCurAddrHtml_1625108329').show();
            }
        }
    });
});

// 优惠券弹出页面
function orderSelectCoupon() {
    var url = orderLinkArr.eyouOrderSelectCoupon;
    //iframe窗
    layer.open({
        type: 2,
        shade: layer_shade,
        area: ['60%', '60%'],
        move: false,
        title: '选择优惠券',
        btnAlign:'r',
        closeBtn: 3,
        shadeClose: false,
        maxmin: false, //开启最大化最小化按钮
        content: url
    });
    event.stopPropagation();
}

// 选择使用优惠券
function selectCoupon(useFindCoupon) {
    if (!useFindCoupon.use_id || undefined === useFindCoupon.use_id) {
        $('#nullCoupon').show();
        $('#selectCoupon').hide();
        $('#useCouponDiv').hide().find('#useCouponDivSpan').html(0);
    } else {
        $('#nullCoupon').hide();
        $('#selectCoupon').show().html('已选优惠券，为您优惠￥ ' + parseFloat(useFindCoupon.coupon_price));
        $('#useCouponDiv').show().find('#useCouponDivSpan').html(parseFloat(useFindCoupon.coupon_price));
    }
}

// 选中收货地址
function selectAddress(idname, addr_id) {
    if (addr_id) {
        $('#' + idname).val(addr_id);
        // 如果存在地址ID则隐藏顶部选择条
        if (parseInt(addr_id) > 0) $('#selectCurAddrHtml_1625108329').hide();

        // 选中效果
        $('.address-item').removeClass('selected');
        $('#' + addr_id + '_ul_li').addClass('selected');

        // 查询运费
        var url = orderLinkArr.eyouInquiryFreight;
        $.ajax({
            url : url,
            data: {addr_id: addr_id, querystr: orderParamArr.querystr},
            type:'post',
            dataType:'json',
            success:function(res) {
                // 重载参数
                orderParamArr.addrID = parseInt(addr_id);
                orderParamArr.allowSubmit = parseInt(res.data.allowSubmit);
                orderParamArr.shippingFee = parseInt(res.data.shippingFee);
                orderParamArr.orderAmount = parseFloat(res.data.orderAmount);
                orderParamArr.orderAmountArr = res.data.orderAmountArr;
                orderParamArr.orderTotalAmount = parseFloat(res.data.orderTotalAmount);

                // 处理订单支付参数
                handleOrderPayParam();

                // 更新运费显示
                $('#shippingFee').empty().html(orderParamArr.shippingFee);
                // 重载商品列表
                $('#shopUnderOrderGoods').empty().html(res.data.goodsHtml);
            }
        });
    }
}

// 使用积分
function useScores(obj) {
    // 是否使用积分进行支付
    orderParamArr.useScorePay = $(obj).is(':checked') ? 1 : 0;

    // 处理订单支付参数
    handleOrderPayParam();
}

// 使用余额
function useBalance(obj) {
    // 是否使用余额进行支付
    orderParamArr.useBalancePay = $(obj).is(':checked') ? 1 : 0;

    // 处理订单支付参数
    handleOrderPayParam();
}

// 处理订单支付参数
function handleOrderPayParam() {
    var orderAmount = parseFloat(orderParamArr.orderAmount);
    if (1 === parseInt(orderParamArr.useScorePay)) {
        // 计算积分抵扣后的商品总额
        orderAmount = Number(orderAmount) - Number(orderParamArr.payUseScores);
    }
    if (1 === parseInt(orderParamArr.useBalancePay)) {
        // 计算余额抵扣后的商品总额
        if (Number(orderParamArr.usersMoney) > Number(orderAmount)) {
            orderParamArr.useMaxMoney = parseFloat(orderAmount);
            orderAmount = 0;
        } else {
            orderParamArr.useMaxMoney = parseFloat(orderParamArr.usersMoney);
            orderAmount = Number(orderAmount) - Number(orderParamArr.useMaxMoney);
        }
    }

    // 显示积分抵扣说明
    if (1 === parseInt(orderParamArr.useScorePay)) {
        $('#useScoresDiv').show().find('#useScoresDivSpan').html(orderParamArr.payUseScores);
        $('#useScoresSpan').show().html('(最多可使用 '+parseInt(orderParamArr.payUseScoresNum)+' 积分，抵扣 '+parseFloat(orderParamArr.payUseScores)+' 元)');
    } else {
        $('#useScoresDiv').hide().find('#useScoresDivSpan').html(0);
        $('#useScoresSpan').hide();
    }

    // 显示余额抵扣说明
    if (1 === parseInt(orderParamArr.useBalancePay)) {
        $('#useBalanceDiv').show().find('#useBalanceDivSpan').html(orderParamArr.useMaxMoney);
        $('#useBalanceSpan').show().html('(最多可使用余额抵扣 ' + parseFloat(orderParamArr.useMaxMoney) + ' 元)');
    } else {
        $('#useBalanceDiv').hide().find('#useBalanceDivSpan').html(0);
        $('#useBalanceSpan').hide();
    }

    // 订单总额 - 优惠券总额
    orderAmount = orderAmount.toFixed(2);
    orderAmountArr = orderAmount.split('.');
    $('#orderAmountArr').empty().html('<em>'+orderAmountArr[0]+'</em>.'+orderAmountArr[1]+'元');
}

// 统一提示方法
function unifiedAlert(msg) {
    layer.alert(msg, {
        move: false,
        closeBtn: 3,
        title: '提示',
        btnAlign: 'r',
        shade: layer_shade,
        area: ['480px', '190px'],
        success: function () {
            $(".layui-layer-content").css('text-align', 'left');
        }
    });
}

// 提交订单
function orderSubmit() {
    // 配送区域提示
    if (0 === parseInt(orderParamArr.allowSubmit)) {
        var msg = 1 === parseInt(orderParamArr.goodsListCount) ? '所选地址不在这个商品配送区域内，请更换地址' : '部分商品不在配送区域内，请移除再提交';
        unifiedAlert(msg);
        return false;
    }
    if (0 === parseInt(orderParamArr.addrID)) {
        unifiedAlert('请选择收货地址');
        return false;
    }
    // 订单备注
    var userNote = $('#userNote').val();
    // 提交的post参数
    var postParam = {
        userNote: userNote,
        useID: useFindCoupon.use_id || 0,
        addrID: orderParamArr.addrID || 0,
        // payName: orderParamArr.payName,
        querystr: orderParamArr.querystr || '',
        __token__: orderParamArr.tokenValue || '',
        useScorePay: orderParamArr.useScorePay || 0,
        useBalancePay: orderParamArr.useBalancePay || 0,
        paymentMethod: orderParamArr.paymentMethod || 0,
    };

    // 显示加载中
    // if (1 === parseInt(orderParamArr.isWeChat) || 1 === parseInt(orderParamArr.isMobile)) {
    //     layer_loading_mini();
    // } else {
    //     layer_loading('正在处理');
    // }

    $.ajax({
        async: false,
        type: 'post',
        data: postParam,
        url : orderLinkArr.eyouOrderSubmit,
        dataType: 'json',
        success: function(res) {
            // if (1 === parseInt(res.code)) {
            //     // 余额支付
            //     if ('balance' == orderParamArr.payName) {
            //         window.location.href = res.url;
            //     }
            //     // 微信支付 or 支付宝支付
            //     else if ('wechat' == orderParamArr.payName || 'alipay' == orderParamArr.payName) {
            //         orderPayApi(res.data.pay_id, res.data.pay_mark, res.data.unified_id, res.data.unified_number, res.data.transaction_type, res.url);
            //     }
            // } else {
            //     layer.closeAll();
            //     unifiedAlert(res.msg);
            // }
        }
    });
}


// 选中收货地址
function SelectEd(idname, addr_id, addrData) {
    if (addr_id) {
        $('#'+idname).val(addr_id);

        if (addrData && $('#addr_consignee')) {
            $('#addr_consignee').html(addrData.consignee);
            $('#addr_mobile').html(addrData.mobile);
            $('#addr_Info').html(addrData.Info);
            $('#addr_address').html(addrData.address);
        } else {
            var lis = $('#UlHtml li');
            var id  = addr_id+'_ul_li';
            $('#'+id).addClass("selected");
            lis.each(function(){
                if (id != this.id) $('#'+this.id).removeClass("selected");
            });
        }

        // 查询运费
        var JsonData = b1decefec6b39feb3be1064e27be2a9;
        var url = JsonData.shop_inquiry_shipping;
        $.ajax({
            url : url,
            data: {addr_id: addr_id, _ajax: 1},
            type:'post',
            dataType:'json',
            success:function(res){
                // 运费
                $('#template_money').html('￥'+res.data);
                
                // 计算总价+运费
                var TotalAmount_old = $('#TotalAmount_old').val();
                var AmountNew = (Number(TotalAmount_old) + Number(res.data)).toFixed(2);
                $('#TotalAmount, #PayTotalAmountID').html(parseFloat(AmountNew));

                // 计算支付后剩余余额
                var UsersMoney = (Number(JsonData.UsersMoney) - Number(AmountNew)).toFixed(2);
                $('#UsersSurplusMoneyID').html(parseFloat(UsersMoney));
            }
        });
    }
}

// 颜色控制
function ColorS(css){
    if ('zxzf' == css) {
        $('#zxzf').addClass("btn-primary");
        $('#hdfk').removeClass("btn-primary");
        $('#payment_method').val(0);
    }else{
        $('#hdfk').addClass("btn-primary");
        $('#zxzf').removeClass("btn-primary");
        $('#payment_method').val(1);
    }
}

// 在微信端时，跳转至选择添加收货地址方式页面
function GetWeChatAddr(){
    var JsonData = b1decefec6b39feb3be1064e27be2a9;
    window.location.href = JsonData.shop_add_address;
}

// 添加收货地址
function ShopAddAddress(){
    var JsonData = b1decefec6b39feb3be1064e27be2a9;
    var url = JsonData.shop_add_address;
    var width  = JsonData.addr_width;
    var height = JsonData.addr_height;
    var isWeChat = JsonData.isWeChat;
    if (url.indexOf('?') > -1) {
        url += '&';
    } else {
        url += '?';
    }
    url += 'type=order';
    if (1 == isWeChat) {
        url += '&gourl='+encodeURIComponent(window.location.href);
        window.location.href = url;
    } else {
        layer.open({
            type: 2,
            shade: layer_shade,
            area: [width, height],
            move: false,
            title: '添加收货地址',
            btnAlign:'r',
            closeBtn: 3,
            shadeClose: false,
            maxmin: false, //开启最大化最小化按钮
            content: url
        }); 
    }
}

// 更新收货地址
function ShopEditAddress(addr_id) {
    var url = orderLinkArr.shopEditAddress;
    var width = orderParamArr.addr_width;
    var height = orderParamArr.addr_height;
    if (url.indexOf('?') > -1) {
        url += '&';
    } else {
        url += '?';
    }
    url += 'addr_id='+addr_id;
    //iframe窗
    layer.open({
        type: 2,
        shade: layer_shade,
        area: [width, height],
        move: false,
        title: '修改收货地址',
        btnAlign:'r',
        closeBtn: 3,
        shadeClose: false,
        maxmin: false, //开启最大化最小化按钮
        content: url
    });
    event.stopPropagation();
}

// 删除收货地址
function ShopDelAddress(addr_id){
    layer.confirm('是否删除收货地址？', {
        shade: layer_shade,
        area: ['480px', '190px'],
        move: false,
        title: '提示',
        btnAlign:'r',
        closeBtn: 3,
        btn: ['是', '否'], //按钮
        success: function () {
            $(".layui-layer-content").css('text-align', 'left');
        }
    }, function () {
        // 是
        var JsonData = b1decefec6b39feb3be1064e27be2a9;
        var url = JsonData.shop_del_address;

        $.ajax({
            url: url,
            data: {addr_id:addr_id,_ajax:1},
            type:'post',
            dataType:'json',
            success:function(res){
                layer.closeAll();
                if ('1' == res.code) {
                    layer.msg(res.msg, {time: 1500});
                    $("#"+addr_id+'_ul_li').remove();
                }else{
                    layer.msg(res.msg, {time: 2000});
                }
            }
        });
    }, function (index) {
        // 否
        layer.closeAll(index);
    });
}

// 邮箱发送
function SendEmail_1608628263(result) {
    var ResultID = 1;
    if (result) {
        $.ajax({
            url: result.url,
            data: result.data,
            type:'post',
            dataType:'json'
        });
    }
    return ResultID;
}

// 手机发送
function SendMobile_1608628263(result) {
    var ResultID = 1;
    if (result) {
        $.ajax({
            url: result.url,
            data: result.data,
            type:'post',
            dataType:'json'
        });
    }
    return ResultID;
}

function goAddressList(obj) {
    var url = $(obj).data('url');
    if (url.indexOf('?') > -1) {
        url += '&';
    } else {
        url += '?';
    }
    url += 'gourl='+encodeURIComponent(window.location.href);
    window.location.href = url;
}